#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import web
import json

from sqlalchemy.orm.exc import NoResultFound
from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils
from Umpweb.base import session, _, render_jinja


render = render_jinja('static/templates/qos', encoding='utf-8',)

class QOSList:

    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.qos()

class QOSCreate:

    def GET(self):
        return render.qos_create()

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())
        body = {"QOSCreate":{'params':values}}
        return utils.web_return(body)

class QOSDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"QOSDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)
        
class QOSUpdate:

    def GET(self):
        x = web.input()
        qos = db_api.qos_get(x.get('id'))
        return render.qos_update(qos=qos)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())

        body = {"QOSUpdate": {'params': values}}
        return utils.web_return(body)

class GridQOS:
    def POST(self):
        web_input = web.input()
        filters = {}
        if not db_api.check_is_adminstrator(session.user.name):
            filters = {'user_id':session.user.id}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.qos_table, web_input, filters=filters)

        for qos in rows:
            volumes = db_api.volume_get_with_qos(qos.id)
            qos.volume_len = len(volumes)

        cells = ['id', 'name', 'throt_iops_avg', 'throt_burst_iops_max', 'throt_burst_iops_time', \
                 'throt_mbps_avg', 'throt_burst_mbps_max', 'throt_burst_mbps_time', \
                 'volume_len', 'username', 'created_at',]

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")

        return rows_json
